import React, {useState, useRef} from 'react';
import {Modal, Button, Table, Space, Input, Select} from 'antd';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';

import axios from 'axios';
import useMemberListModel from './memberList';
import useDidMount from '../../hooks/useDidMount';
import useGlobal from '../../hooks/useGlobal';
import imgUrlBase from '../../helpers/imgUrlBase';

const {Option} = Select;

const STATUS_TEXT_MAP = {
  '2': '待审核',
  '1': '已通过',
  '0': '已驳回',
  '4': '已离退'
};

const defaultColumns = [
  {title: '姓名', dataIndex: 'cname', render: text => <span style={{color: '#1890ff'}}>{text}</span>},
  {title: '性别', dataIndex: 'sex'},
  {title: '学校', dataIndex: 'school_name'},
  {title: '毕业年份', dataIndex: 'year'},
  {title: '专业', dataIndex: 'major'},
  {title: '职务', dataIndex: 'job'},
  {title: '电话', dataIndex: 'phone'},
  {title: '邮箱', dataIndex: 'email'},
];

function Member() {

  const Global = useGlobal();
  const tableRef = useRef();

  // table 规范
  const columns = {
    wait: [
      ...defaultColumns,
      {
        title: '操作', render: (text, record) => {
          return (
            <Space size="middle">
              <Button onClick={e => handleModalShow_wait(record, e)}>详情</Button>
            </Space>
          );
        }
      },
    ],
    pass: [
      ...defaultColumns,
      {title: '备注', dataIndex: 'memo'},
      {title: '测评分数', dataIndex: 'assess'},
      {
        title: '操作', render: (text, record) => {
          return (
            <Space size="middle">
              <Button onClick={e => handleModalShow_finished(record, e)}>详情</Button>
            </Space>
          );
        }
      },
    ],
    reject: [
      ...defaultColumns,
      {title: '备注', dataIndex: 'memo'},
      {
        title: '操作', render: (text, record) => {
          return (
            <Space size="middle">
              <Button onClick={e => handleModalShow_finished(record, e)}>详情</Button>
            </Space>
          );
        }
      },
    ],
    quit: [
      ...defaultColumns,
      {title: '备注', dataIndex: 'memo'},
      {title: '测评分数', dataIndex: 'assess'},
      {
        title: '操作', render: (text, record) => {
          return (
            <Space size="middle">
              <Button onClick={e => handleModalShow_finished(record, e)}>详情</Button>
            </Space>
          );
        }
      },
    ],
    export: [
      ...defaultColumns,
      {title: '审核状态', dataIndex: 'status', render: text => STATUS_TEXT_MAP[String(text)]},
      {title: '备注', dataIndex: 'memo'},
    ]
  };

  // all-list
  const [curStatus, setCurStatus] = useState('wait');
  const MemberListModel = useMemberListModel();


  useDidMount(() => {
    MemberListModel.effect.getMemberList();
    // 设置table的id、绑定到excel导出
    tableRef.current.querySelector('table').setAttribute('id', 'table-to-xls');
  });


  const [modalVisible, setModalVisible] = useState(null);
  const [modalContent, setModalContent] = useState({});

  const handleModalExit = () => {
    setModalVisible(null);
    setModalContent({});
  };

  // Modal_wait
  const handleModalShow_wait = content => {
    setModalVisible('wait');
    setModalContent(content);
  };
  const handlePassFail = (id, status) => {
    let url = 'https://evp.51job.com/51job/api/1.0/index.php/msd/admin/setuserstatus?token=' + Global.state.login?.token + '&userid=' + id + '&status=' + status;
    axios.get(url).then(res => {
      if (res.data.code === 1000 && res.data.msg === '验证错误') {
        Global.effect.setLogin(null);
        localStorage.clear();
      } else {
        // getList();
        handleModalExit();
      }
    });
  };

  // Modal_finished
  const handleModalShow_finished = content => {
    setModalVisible('pass');
    setModalContent(Object.assign({}, content));
  };

  const handleEditText = (type, e) => {
    setModalContent(Object.assign({}, modalContent, {[type]: e.target.value}));
  };
  const handleJobChange = i => {
    setModalContent(Object.assign({}, modalContent, {job: i}));
  };

  const handleEdit = async content => {
    await MemberListModel.effect.editMember({
      userid: content.id,
      cname: content.cname,
      sex: content.sex,
      year: content.year,
      major: content.major,
      job: content.job,
      phone: content.phone,
      email: content.email,
      memo: content.memo,
      assess: content.assess
    });
    handleModalExit();
  };

  const handleQuit = async content => {
    Modal.confirm({
      title: '离退确认',
      content: '确认离退该用户吗？',
      onOk: () => {
        MemberListModel.effect.memberQuit(content.id);
        handleModalExit();
      }
    });
  };

  return (
    <div style={{padding: '40px'}}>

      <div style={{marginBottom: '20px'}}>
        <Button style={{margin: '0 20px'}} type={curStatus === 'wait' ? 'primary' : 'ghost'}
                onClick={() => setCurStatus('wait')}>待审核</Button>
        <Button style={{margin: '0 20px'}} type={curStatus === 'pass' ? 'primary' : 'ghost'}
                onClick={() => setCurStatus('pass')}>已审核</Button>
        <Button style={{margin: '0 20px'}} type={curStatus === 'reject' ? 'primary' : 'ghost'}
                onClick={() => setCurStatus('reject')}>已驳回</Button>
        <Button style={{margin: '0 20px'}} type={curStatus === 'quit' ? 'primary' : 'ghost'}
                onClick={() => setCurStatus('quit')}>已离退</Button>
        <ReactHTMLTableToExcel
          id="test-table-xls-button"
          className="download-table-xls-button"
          table="table-to-xls"
          filename="tablexls"
          sheet="tablexls"
          buttonText="导出Excel"
        />
      </div>

      {/* 不分页的table 以供导出excel */}
      <div ref={tableRef}>
        <Table
          columns={columns.export}
          dataSource={MemberListModel.state.allList}
          pagination={false}
          style={{display: 'none'}}
        />
      </div>

      {/* 页面展示table */}
      <div>
        <Table
          columns={columns[curStatus]}
          dataSource={MemberListModel.state[`${curStatus}List`]}
          pagination={{position: ['bottomCenter'], defaultPageSize: 8}}
        />
      </div>

      {/* 待审核页的详细信息弹窗 */}
      <Modal title="详细信息" visible={modalVisible === 'wait'} onCancel={handleModalExit} footer={[
        <Button key="pass" onClick={() => handlePassFail(modalContent.id, 1)}>通过</Button>,
        <Button key="no-pass" onClick={() => handlePassFail(modalContent.id, 0)}>不通过</Button>
      ]}
      >
        <p>姓名：{modalContent.cname}</p>
        <p>性别：{modalContent.sex}</p>
        <p>毕业年份：{modalContent.year}</p>
        <p>专业：{modalContent.major}</p>
        <p>职位：{modalContent.job}</p>
        <p>电话：{modalContent.phone}</p>
        <p>邮箱：{modalContent.email}</p>
        <p>学校名：{modalContent.school_name}</p>
        <p>学生证：<img style={{verticalAlign: 'top', height: '120px'}}
                    onClick={() => {
                      Modal.info({
                        title: '学生证',
                        icon: null,
                        width: 800,
                        content: <img src={imgUrlBase(modalContent.student_cert) + modalContent.student_cert}
                                      style={{width: '100%'}}
                                      alt=""/>
                      });
                    }}
                    src={imgUrlBase(modalContent.student_cert) + modalContent.student_cert} alt=""/></p>
      </Modal>

      {/* 已审核页的详细信息弹窗 */}
      <Modal title="详细信息" visible={modalVisible === 'pass'} onCancel={handleModalExit} footer={[
        <Button key="edit" onClick={() => handleEdit(modalContent)}>修改</Button>,
        modalContent.status === 1 && <Button key="quit" onClick={() => handleQuit(modalContent)} danger>离退</Button>
      ]}
      >
        <p>姓名：<Input style={{width: '320px'}} value={modalContent.cname} onChange={e => handleEditText('cname', e)}/>
        </p>
        <p>性别：<Input style={{width: '320px'}} value={modalContent.sex} onChange={e => handleEditText('sex', e)}/></p>
        <p>毕业年份：<Input style={{width: '320px'}} value={modalContent.year} onChange={e => handleEditText('year', e)}/>
        </p>
        <p>专业：<Input style={{width: '320px'}} value={modalContent.major} onChange={e => handleEditText('major', e)}/>
        </p>
        <div style={{marginBottom: '10px'}}>职位：
          <Select style={{width: '320px'}} value={modalContent.job} onChange={handleJobChange}>
            {
              <>
                <Option value='主席' key='主席'>主席</Option>
                <Option value='副主席' key='副主席'>副主席</Option>
                <Option value='部长' key='部长'>部长</Option>
                <Option value='副部长' key='副部长'>副部长</Option>
                <Option value='成员' key='成员'>成员</Option>
              </>
            }
          </Select>
        </div>
        <p>电话：<Input style={{width: '320px'}} value={modalContent.phone} onChange={e => handleEditText('phone', e)}/>
        </p>
        <p>邮箱：<Input style={{width: '320px'}} value={modalContent.email} onChange={e => handleEditText('email', e)}/>
        </p>
        <p>备注：<Input style={{width: '320px'}} value={modalContent.memo} onChange={e => handleEditText('memo', e)}/></p>
        <p>测评分数：<Input style={{width: '320px'}}
                       disabled={Global.state.login.auth !== '0'}
                       value={modalContent.assess}
                       onChange={e => handleEditText('assess', e)}/></p>
        <p>学校名：{modalContent.school_name}</p>
        <p>学生证：<img style={{verticalAlign: 'top', height: '120px'}}
                    onClick={() => {
                      Modal.info({
                        title: '学生证',
                        icon: null,
                        width: 800,
                        content: <img src={imgUrlBase(modalContent.student_cert) + modalContent.student_cert}
                                      style={{width: '100%'}}
                                      alt=""/>
                      });
                    }}
                    src={imgUrlBase(modalContent.student_cert) + modalContent.student_cert} alt=""/></p>
      </Modal>
    </div>
  );
}

export default Member;